package com._51doit.spark05

import java.sql.{Connection, PreparedStatement}

object IpUtils {

  //定义一个释放资源的方法  conn获取数据库链接  pstm1 创建表-  pstm2 插入数据-
  def closeconn(conn: Connection, pstm1: PreparedStatement, pstm2: PreparedStatement) = {
    if (pstm2 != null) pstm2.close()
    if (pstm1 != null) pstm1.close()
    if (conn != null) conn.close()
  }

  def binarySearch(longIp: Long, rules: Array[(Long, Long, String)]): String = {
    // 定义大小2个指针
    var low = 0
    var high = rules.length - 1
    while (low <= high) {
      // 获取中间索引
      val middle = (low + high) / 2
      // 获取中间位置的值
      val (start, end, province) = rules(middle)
      if (longIp >= start && longIp <= end) {
        // 必须要有返回值
        return province
      } else if (longIp < start) { // 左边区间
        high = middle - 1
      } else { // 右区间
        low = middle + 1
      }
    }
    // 程序执行到此位置 没找到
    "unknown"
  }

  // 定义一个方法，把 定义一个方法，把 ip 地址转换为 地址转换为 10 进制
  def ip2Long(ip: String) = {
    val split = ip.split("\\.")
    var inum = 0L
    for (i <- 0 until split.length) {
      inum = split(i).toLong | inum << 8L
    }
    inum
  }



}
